﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using ChinaCustoms.Qingdao.Workflow.Web;
using ChinaCustoms.Qingdao.Workflow.Supports;
using Tunynet.QingdaoCustoms.Data.Utils;
using ChinaCustoms.Qingdao.Workflow.Permissions;
using ChinaCustoms.Qingdao.Workflow.Controls;
using System.Text;

public partial class ManageTasks : ManageBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        TasksRepeater.ItemDataBound += new RepeaterItemEventHandler(TasksRepeater_ItemDataBound);
        TasksRepeater.ItemCommand += new RepeaterCommandEventHandler(TasksRepeater_ItemCommand);

        if (!this.IsPostBack)
        {
            StatusDropDownList.Items.Clear();
            StatusDropDownList.Items.Add(new ListItem("不限", string.Empty));
            StatusDropDownList.Items.Add(new ListItem("运行中", ((int)TaskStatus.Executing).ToString()));
            StatusDropDownList.Items.Add(new ListItem("已完成", ((int)TaskStatus.Completed).ToString()));
            StatusDropDownList.Items.Add(new ListItem("已终止", ((int)TaskStatus.Terminated).ToString()));
            StatusDropDownList.Items.Add(new ListItem("未生效", ((int)TaskStatus.Creating).ToString()));

            DateScopeDropDownList.Items.Clear();
            DateScopeDropDownList.Items.Add(new ListItem("不限", string.Empty));
            DateScopeDropDownList.Items.Add(new ListItem("一天内", ((int)DateScope.InOneDays).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("两天内", ((int)DateScope.InTwoDays).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("五天内", ((int)DateScope.InFiveDays).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("一周内", ((int)DateScope.InOneWeeks).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("两周内", ((int)DateScope.InTwoWeeks).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("一月内", ((int)DateScope.InOneMonths).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("两月内", ((int)DateScope.InTwoMonths).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("四月内", ((int)DateScope.InFourMonths).ToString()));
            DateScopeDropDownList.Items.Add(new ListItem("一年内", ((int)DateScope.InOneYears).ToString()));


            if (!string.IsNullOrEmpty(Request.QueryString["TaskName"]))
                TaskName.Text = Request.QueryString["TaskName"];

            if (!string.IsNullOrEmpty(Request.QueryString["SponsorUserName"]))
                SponsorUserName.Text = Request.QueryString["SponsorUserName"];

            if (!string.IsNullOrEmpty(Request.QueryString["Status"]))
            {
                ListItem li = StatusDropDownList.Items.FindByValue(Request.QueryString["Status"]);
                if (li != null)
                    li.Selected = true;
            }

            if (!string.IsNullOrEmpty(Request.QueryString["DateScope"]))
            {
                ListItem li = DateScopeDropDownList.Items.FindByValue(Request.QueryString["DateScope"]);
                if (li != null)
                    li.Selected = true;
            }

            TasksRepeaterDataBind();
        }
    }

    void TasksRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        switch (e.Item.ItemType)
        {
            case ListItemType.AlternatingItem:
            case ListItemType.Item:
                TaskInfo task = e.Item.DataItem as TaskInfo;
                if (task != null)
                {
                    HyperLink taskName = e.Item.FindControl("TaskName") as HyperLink;
                    if (taskName != null)
                    {
                        taskName.Text = task.TaskName;
                        taskName.NavigateUrl = string.Format("~/WorkflowTracking.aspx?TaskID={0}", task.TaskGuid);
                    }

                    Literal applicationName = e.Item.FindControl("ApplicationName") as Literal;
                    if (applicationName != null)
                        applicationName.Text = task.ApplicationName;

                    Literal sponsorDisplayName = e.Item.FindControl("SponsorDisplayName") as Literal;
                    if (sponsorDisplayName != null)
                        sponsorDisplayName.Text = task.SponsorDisplayName;

                    Literal sponsorOrganization = e.Item.FindControl("SponsorOrganization") as Literal;
                    if (sponsorOrganization != null)
                        sponsorOrganization.Text = PermissionUtils.StripDisplayNameFromUserFullPath(task.SponsorFullPath);

                    Literal createDate = e.Item.FindControl("CreateDate") as Literal;
                    if (createDate != null)
                        createDate.Text = task.CreateDate.ToShortDateString();

                    Literal status = e.Item.FindControl("Status") as Literal;
                    if (status != null)
                        status.Text = task.StatusText;

                    Literal executingActivityName = e.Item.FindControl("ExecutingActivityName") as Literal;
                    if (executingActivityName != null)
                        executingActivityName.Text = task.ExecutingStepName;

                    LinkButton restartButton = e.Item.FindControl("RestartButton") as LinkButton;
                    if (restartButton != null && task.Status == TaskStatus.Completed)
                    {
                        restartButton.Visible = true;
                        restartButton.CommandArgument = task.TaskGuid.ToString();
                        restartButton.Attributes["onclick"] = "if (!confirm(\"确定要重新启动该任务吗？\")) return false;";
                    }

                    LinkButton terminateButton = e.Item.FindControl("TerminateButton") as LinkButton;
                    if (terminateButton != null && task.Status == TaskStatus.Executing)
                    {
                        terminateButton.Visible = true;
                        terminateButton.CommandArgument = task.TaskGuid.ToString();
                        terminateButton.Attributes["onclick"] = "if (!confirm(\"确定要终止该任务吗？\")) return false;";
                    }

                    LinkButton deleteButton = e.Item.FindControl("DeleteButton") as LinkButton;
                    if (deleteButton != null)
                    {
                        deleteButton.CommandArgument = task.TaskGuid.ToString();
                        deleteButton.Attributes["onclick"] = "if (!confirm(\"确定要删除该任务吗？\")) return false;";
                    }

                    HyperLink handoverLink = e.Item.FindControl("HandoverLink") as HyperLink;
                    if (handoverLink != null && task.Status == TaskStatus.Executing)
                    {
                        handoverLink.Visible = true;
                        handoverLink.NavigateUrl = "~/HandoverWorkItem.aspx?TaskGuid=" + task.TaskGuid;
                    }
                }

                break;
        }
    }

    void TasksRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        Guid taskGuid = new Guid(e.CommandArgument.ToString());

        switch (e.CommandName)
        {
            case "Restart":
                Tasks.RestartTask(taskGuid);
                Response.Redirect(Request.RawUrl, true);
                break;

            case "Terminate":                
                Tasks.TerminateTask(taskGuid);
                Response.Redirect(Request.RawUrl, true);
                break;

            case "Delete":                
                Tasks.DeleteTask(taskGuid);
                Response.Redirect(Request.RawUrl, true);
                break;
        }
    }

    protected void SearchButton_Click(object sender, EventArgs e)
    {
        StringBuilder queryString = new StringBuilder();

        if (!string.IsNullOrEmpty(TaskName.Text.Trim()))
            queryString.AppendFormat("TaskName={0}", Server.UrlEncode(TaskName.Text.Trim()));

        if (!string.IsNullOrEmpty(SponsorUserName.Text.Trim()))
            queryString.AppendFormat("SponsorUserName={0}", SponsorUserName.Text.Trim());

        if (!string.IsNullOrEmpty(StatusDropDownList.SelectedValue))
            queryString.AppendFormat("Status={0}", StatusDropDownList.SelectedValue);

        if (!string.IsNullOrEmpty(DateScopeDropDownList.SelectedValue))
            queryString.AppendFormat("DateScope={0}", DateScopeDropDownList.SelectedValue);

        Response.Redirect(Request.Url.AbsolutePath + "?" + queryString.ToString(), true);
    }

    void TasksRepeaterDataBind()
    {
        TaskQuery query = new TaskQuery();

        if (!IsAdministrator)
            query.ApplicationCodeNames = this.ApplicationCodeNamesForManager.ToArray();

        if (!string.IsNullOrEmpty(TaskName.Text.Trim()))
            query.TaskName = TaskName.Text.Trim();

        if (!string.IsNullOrEmpty(SponsorUserName.Text.Trim()))
            query.SponsorUserName = SponsorUserName.Text.Trim();

        if (!string.IsNullOrEmpty(StatusDropDownList.SelectedValue))
            query.TaskStatus = (TaskStatus)int.Parse(StatusDropDownList.SelectedValue);

        if (!string.IsNullOrEmpty(DateScopeDropDownList.SelectedValue))
            query.DateScope = (DateScope)int.Parse(DateScopeDropDownList.SelectedValue);

        query.PageIndex = Pager1.PageIndex;

        PagingDataSet<TaskInfo> tasks = Tasks.GetTasks(query);

        Pager1.PageSize = query.PageSize;
        Pager1.TotalRecords = tasks.TotalRecords;

        TasksRepeater.DataSource = tasks.Records;
        TasksRepeater.DataBind();
    }

}
